import React, { useEffect } from "react";
import "./mapArea.css";
import { Map, View } from "ol";
import TileLayer from "ol/layer/Tile";
import OSM from "ol/source/OSM";
import "ol/ol.css";
import { fromLonLat, toLonLat } from "ol/proj";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";
import { Circle as CircleStyle, Fill, Style, Stroke, Icon } from "ol/style"; // 新增标记点
import Overlay from "ol/Overlay";

// 创建地图
const Main = ({ markerCoords, setSelectedMarker, treeData }) => {
  useEffect(() => {
    const map = new Map({
      view: new View({
        center: fromLonLat([116.35167, 39.88305]), // 北京的地理坐标
        zoom: 10, // 初始放大倍率
      }),
      layers: [
        new TileLayer({
          source: new OSM(),
        }),
      ],
      target: "map",
    });

    const createMarker = (lon, lat, title, isNew) => {
      const marker = new Feature({
        geometry: new Point(fromLonLat([lon, lat])),
        title,
      });
      const defaultIconStyle = isNew
        ? // 新增点位样式 三目判断
          new Style({
            image: new CircleStyle({
              radius: 7,
              fill: new Fill({ color: "red" }),
              stroke: new Stroke({
                color: [255, 0, 0],
                width: 3,
              }),
            }),
          })
        : new Style({
            image: new Icon({
              anchor: [0.5, 1],
              src: "https://openlayers.org/en/latest/examples/data/icon.png",
            }),
          });

      // 悬浮放大
      const hoverIconStyle = new Style({
        image: new Icon({
          anchor: [0.5, 1],
          src: "https://openlayers.org/en/latest/examples/data/icon.png",
          scale: 1.5, // 放大 1.5 倍
        }),
      });

      marker.setStyle(defaultIconStyle);
      marker.set("defaultStyle", defaultIconStyle);
      marker.set("hoverStyle", hoverIconStyle);
      return marker;
    };
    const vectorSource = new VectorSource();

    // 初始化五个点位
    const initialMarkers = [
      {
        lon: 116.35167,
        lat: 39.88305,
        title: "天安门",
      },
      {
        lon: 116.65167,
        lat: 39.88305,
        title: "天坛公园",
      },
      {
        lon: 116.55167,
        lat: 40.12305,
        title: "雍和宫",
      },
      {
        lon: 116.05167,
        lat: 39.52305,
        title: "恭王府",
      },
      {
        lon: 116.01167,
        lat: 40.02305,
        title: "前门大街",
      },
    ];

    // 将初始标记添加到矢量数据源
    initialMarkers.forEach(({ lon, lat, title }) => {
      vectorSource.addFeature(createMarker(lon, lat, title, false));
    });

    // 将新添加的标记添加到矢量数据源
    markerCoords.forEach(({ lon, lat, title }) => {
      vectorSource.addFeature(createMarker(lon, lat, title, true));
      map.getView().setCenter(fromLonLat([lon, lat]));
    });

    // 创建并添加矢量图层
    const vectorLayer = new VectorLayer({
      source: vectorSource,
    });
    map.addLayer(vectorLayer); // 将矢量图层添加到地图

    const tooltipElement = document.createElement("div");
    tooltipElement.className = "ol-tooltip ol-tooltip-hidden";
    const overlay = new Overlay({
      element: tooltipElement,
      offset: [10, 0],
      positioning: "bottom-left",
    });
    map.addOverlay(overlay);

    // 监听鼠标移动事件，用于显示点位浮窗提示
    map.on("pointermove", (event) => {
      const feature = map.forEachFeatureAtPixel(
        event.pixel,
        (feature) => feature
      );
      if (feature) {
        const coords = feature.getGeometry().getCoordinates();
        const [lon, lat] = toLonLat(coords);
        const title = feature.get("title");
        // 数据展示
        tooltipElement.innerHTML = `${title} <br/> 经度: ${lon.toFixed(
          2
        )}, 纬度: ${lat.toFixed(2)}`;
        overlay.setPosition(coords);
        tooltipElement.classList.remove("ol-tooltip-hidden");
        // 设置悬浮样式
        feature.setStyle(feature.get("hoverStyle"));
      } else {
        tooltipElement.classList.add("ol-tooltip-hidden");

        // 恢复默认样式
        vectorSource
          .getFeatures()
          .forEach((f) => f.setStyle(f.get("defaultStyle")));
      }
    });

    // 监听点击事件，用于设置选中的标记
    map.on("click", (event) => {
      // 获取点击位置的要素（标记）
      const feature = map.forEachFeatureAtPixel(
        event.pixel,
        (feature) => feature
      );
      if (feature) {
        // 获取要素的几何坐标
        const coords = feature.getGeometry().getCoordinates();
        // 将坐标转换为经纬度
        const [lon, lat] = toLonLat(coords);
        // 获取要素的标题
        const title = feature.get("title");
        setSelectedMarker({ lon, lat, title }); // 删除功能：更新选中的标记
        console.log(title); // 检查标记的标题
        console.log(treeData); // 检查树信息数据
        // 根据标题查找对应的树信息
        const treeInfo = treeData[title];

        if (treeInfo) {
          setSelectedMarker({
            lon,
            lat,
            title,
            name: treeInfo.name,
            number: treeInfo.number,
            age: treeInfo.age,
            type: treeInfo.type,
          });
        } else {
          setSelectedMarker({
            lon,
            lat,
            title,
          });
        }
      }
    });

    // 清理函数，在组件卸载时移除地图
    return () => {
      if (map) {
        map.setTarget(null);
      }
    };
  }, [markerCoords, setSelectedMarker, treeData]);

  return (
    <div
      id="map"
      className="map"
      style={{ width: "100%", height: "100vh" }}
    ></div>
  );
};

export default Main;
